package com.jh.fcsm.filter;

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.jh.fcsm.beans.sys.vo.LoginUser;
import com.jh.fcsm.constant.RedisConstant;
import com.jh.fcsm.constant.TokenConstants;
import com.jh.fcsm.service.sys.TokenService;
import com.jh.fcsm.util.security.RSAEncrypt;
import com.jh.fcsm.util.txt.StringUtils;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * Token过滤器
 */
@Component
public class TokenFilter extends OncePerRequestFilter {

    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private TokenService tokenService;

    @Qualifier("userDetailsServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = tokenService.getToken(request);
        if (StringUtils.isNotBlank(token)) {
            Object loginUser = tokenService.getLoginUser(token);
            if (loginUser != null) {

                loginUser = checkLoginTime(loginUser);
                if (loginUser instanceof LoginUser) {
                    LoginUser user = (LoginUser) loginUser;
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        /**
         * 前台页面数据传输加密处理方法
         */
        //要放行的不用加密的url  注意，这里要与前台配合使用
        String [] url={"/sys/login"};
        boolean isFound = Arrays.stream(url).anyMatch(request.getRequestURI()::contains);
        //只在正式环境下生效,登录接口排除，单独加密
        if(!"prod".equals(active)||isFound){
            filterChain.doFilter(request, response);
            return ;
        }
        String method = request.getMethod();
        if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method))&&request.getHeader("Accept").contains("json")) {
            String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            if(StringUtils.isEmpty(body)){
                filterChain.doFilter(request, response);
                return ;
            }
            String sm4mm = null;
            String requestBody=null;
            try {

                sm4mm = decryptBody(body.split("@")[1]);
//                sm4mm= new String(Base64.decodeBase64(sm4mm), StandardCharsets.UTF_8);
                requestBody=new String(Base64.decodeBase64(decrypt(body.split("@")[0],sm4mm)), StandardCharsets.UTF_8);
            } catch (Exception e) {
                throw new RuntimeException("非法请求");
            }

            String finalDecryptedBody = requestBody;
            HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
                @Override
                public ServletInputStream getInputStream() {
                    return new ServletInputStreamWrapper(finalDecryptedBody.getBytes(StandardCharsets.UTF_8));
                }
                @Override
                public BufferedReader getReader() {
                    return new BufferedReader(new InputStreamReader(this.getInputStream()));
                }
            };
            filterChain.doFilter(wrapper, response);
        } else {
            filterChain.doFilter(request, response);
        }
    }

    private String decryptBody(String body) throws Exception {
        // 在这里添加解密逻辑
        return RSAEncrypt.privateKeyDecrypt(body,TokenConstants.PRIVATE_KEY);
    }

    private String decrypt(String value,String secret) throws Exception {
        SymmetricCrypto sm4 = SmUtil.sm4(secret.getBytes());
        return sm4.decryptStr(value,StandardCharsets.UTF_8);//库解密结果
    }

    /**
     * 校验时间<br>
     * 过期时间与当前时间对比，临近过期10分钟内的话，自动刷新缓存
     *
     * @param loginUser 登录用户
     * @return 登录用户
     */
    private Object checkLoginTime(Object loginUser) {
        if (loginUser instanceof LoginUser) {
            LoginUser user = (LoginUser) loginUser;
            long expireTime = user.getExpireTime();
            long currentTime = System.currentTimeMillis();
            if (expireTime - currentTime <= RedisConstant.REDIS_EXPIRE_TEN_MINUTES) {
                String token = user.getToken();
                user = (LoginUser) userDetailsService.loadUserByUsername(user.getUsername());
                user.setToken(token);
                tokenService.refresh(user);
            }
            loginUser = user;
        }
        return loginUser;
    }

}
